import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wisave/widgets/indicator.dart';
import 'package:flutter_wisave/widgets/lineChartSample.dart';
import 'package:flutter_wisave/widgets/LineChartSampleSteel.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'SteelItem.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../../widgets/AppColors.dart';
import '../../Tools/ToolsLocalStorage.dart';

class SteelView extends StatefulWidget {
  const SteelView({super.key});

  @override
  State<SteelView> createState() => _SteelViewState();
}

class _SteelViewState extends State<SteelView>
    with SingleTickerProviderStateMixin {
  final NetworkService _networkService = NetworkService();

  Map<String, dynamic> _billetData = {};
  List<dynamic> listData = [];
  get controller => null;

  // 定义一个变量来管理选中的值
  List<String> _selectedCheckboxes = ['index:0', 'index:1'];
  String _selectedCountLabel = '已选2项';

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _loadData('');
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadListData('');
  }

  Future<void> _loadData(String pdiId) async {
    try {
      final result = await _fetchLoadData(pdiId);
      if (result['code'] == 200 && result['data'] != null) {
        setState(() {
          _billetData = result['data'] as Map<String, dynamic>;
          print('_billetData==========================: ${_billetData}');
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchLoadData(String pdiId) async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.get(
          '/plcTimer/billetdischargehistory/selectInfo?companyId=$deptID&pdiId=$pdiId');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('oxidationloss/avgInfo Failed to load data');
      }
    } catch (e) {
      print('oxidationloss/avgInfo Error in _fetchData: $e');
      rethrow;
    }
  }

  //曲线数据
  Future<void> _loadListData(String pdiId) async {
    try {
      final result = await _fetchData(pdiId);
      if (result['code'] == 200 && result['temp'] != null) {
        if (mounted) {
          setState(() {
            listData = (result['temp'] as List)
                .map((item) => (item as Map<String, dynamic>))
                .toList();
            print('getBilletTempList==========================: ${listData}');
          });
        }
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData(String pdiId) async {
    try {
      final response = await _networkService
          .get('/plcTimer/billettemptracking/getBilletTempList?pdiId=$pdiId');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('oxidationloss/avgInfo Failed to load data');
      }
    } catch (e) {
      print('oxidationloss/avgInfo Error in _fetchData: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(15.0),
      margin: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
      decoration: const BoxDecoration(
        color: Colors.transparent,
      ),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Container(
                    padding: EdgeInsets.only(left: 10),
                    decoration: BoxDecoration(
                      color: AppColors.cardColor,
                      borderRadius: BorderRadius.circular(11),
                    ),
                    child: SizedBox(
                      width: MediaQuery.of(context).size.width - 112,
                      child: TextField(
                        decoration: InputDecoration(
                          icon: Image.asset('assets/images/centre/search.png'),
                          hintText: '请输入钢坯编码',
                          border: InputBorder.none,
                        ),
                        onSubmitted: (String text) {
                          _loadData(text);
                          _loadListData(text);
                        },
                      ),
                    ),
                  ),
                  // TDInput(
                  //   type: TDInputType.cardStyle,
                  //   width: MediaQuery.of(context).size.width - 112,
                  //   controller: controller,
                  //   leftIcon: Image.asset('assets/images/centre/search.png'),
                  //   hintText: '请输入钢坯编号',
                  //   hintTextStyle: TextStyle(color: AppColors.textPrimary),
                  //   backgroundColor: Colors.transparent,
                  //   textInputBackgroundColor: AppColors.cardColor,
                  //   needClear: false,
                  //   onSubmitted: (text) {
                  //     _loadData(text);
                  //     _loadListData(text);
                  //   },
                  //   decoration: BoxDecoration(
                  //     color: Colors.transparent,
                  //     border: Border.all(color: AppColors.dividerColor),
                  //     borderRadius: BorderRadius.circular(8.0),
                  //   ),
                  // ),
                  const SizedBox(
                    width: 20,
                  ),
                  Text(
                    '取消',
                    style:
                        TextStyle(fontSize: 16, color: AppColors.textPrimary),
                  ),
                ],
              ),
            ],
          ),
          if (_billetData.isNotEmpty) ...[
            const SizedBox(height: 10),
            Padding(
              padding: const EdgeInsets.all(0.0),
              child: Container(
                padding: const EdgeInsets.all(16.0),
                decoration: BoxDecoration(
                  color: AppColors.cardColor,
                  borderRadius: BorderRadius.circular(8.0),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.2),
                      blurRadius: 6.0,
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '钢坯详细信息',
                      style:
                          TextStyle(fontSize: 16, color: AppColors.textPrimary),
                    ),
                    const SizedBox(height: 10),
                    ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: 7,
                      itemBuilder: (context, index) {
                        return SteelItem(
                          data: _billetData,
                          index: index,
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 10),
            Padding(
              padding: const EdgeInsets.all(0.0),
              child: Container(
                padding: const EdgeInsets.all(16.0),
                decoration: BoxDecoration(
                  color: AppColors.cardColor,
                  borderRadius: BorderRadius.circular(8.0),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.2),
                      blurRadius: 6.0,
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        TDText(
                          '钢坯温度',
                          textColor: AppColors.textPrimary,
                          font: TDTheme.of(context).fontBodyMedium,
                        ),
                        TDText(
                          '(℃)',
                          font: TDTheme.of(context).fontBodyMedium,
                          textColor: AppColors.textSecondary,
                          fontWeight: FontWeight.bold,
                        ),
                        const Expanded(child: SizedBox()),
                        const SizedBox(width: 3),
                        GestureDetector(
                          onTap: () {
                            Navigator.of(context).push(TDSlidePopupRoute(
                                modalBarrierColor:
                                    TDTheme.of(context).fontGyColor2,
                                slideTransitionFrom: SlideTransitionFrom.bottom,
                                builder: (context) {
                                  return TDPopupBottomConfirmPanel(
                                    title: '选择钢坯温度分类',
                                    leftClick: () {
                                      Navigator.maybePop(context);
                                    },
                                    rightTextColor: Color(0xFF2AB6F7),
                                    rightClick: () {
                                      // TDToast.showText('确定', context: context);
                                      print(
                                          'Selected IDs: $_selectedCheckboxes');
                                      setState(() {
                                        _selectedCountLabel =
                                            '已选${_selectedCheckboxes.length}项';
                                      });
                                      Navigator.maybePop(context);
                                    },
                                    child: Container(
                                        height: 200,
                                        child: TDCheckboxGroupContainer(
                                          selectIds: _selectedCheckboxes,
                                          cardMode: true,
                                          direction: Axis.horizontal,
                                          directionalTdCheckboxes: [
                                            for (var i = 0; i < 6; i++)
                                              TDCheckbox(
                                                id: 'index:$i',
                                                title: [
                                                  '下面',
                                                  '芯部',
                                                  '上面',
                                                  '断面',
                                                  '上炉',
                                                  '下炉'
                                                ][i],
                                                cardMode: true,
                                                selectColor: Color(0xFF2AB6F7),
                                                onCheckBoxChanged: (checked) {
                                                  setState(() {
                                                    if (checked) {
                                                      _selectedCheckboxes
                                                          .add('index:$i');
                                                    } else {
                                                      _selectedCheckboxes
                                                          .remove('index:$i');
                                                    }
                                                    print(
                                                        'Selected Checkboxes: $_selectedCheckboxes');
                                                  });
                                                },
                                              ),
                                          ],
                                        )),
                                  );
                                }));
                          },
                          child: Row(
                            children: [
                              TDText(
                                _selectedCountLabel,
                                font: TDTheme.of(context).fontBodySmall,
                                textColor: Color(0xFF2AB6F7),
                              ),
                              Icon(
                                TDIcons.chevron_down,
                                color: Color(0xFF2AB6F7),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                    const SizedBox(height: 10), // Add some space
                    const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Indicator(
                          color: Color(0xFF2AB6F7),
                          text: '下面',
                          isSquare: true,
                          size: 12,
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Indicator(
                          color: Color(0xFF814FF3),
                          text: '芯部',
                          isSquare: true,
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Indicator(
                          color: Color(0xFF53E0B1),
                          text: '上面',
                          isSquare: true,
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Indicator(
                          color: Color(0xFFFCAA3F),
                          text: '断面',
                          isSquare: true,
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Indicator(
                          color: Color(0xFFEF6B9C),
                          text: '上炉',
                          isSquare: true,
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Indicator(
                          color: Color(0xFFFD5864),
                          text: '下炉',
                          isSquare: true,
                        ),
                      ],
                    ),
                    const SizedBox(height: 10), // Add some space
                    LineChartSampleSteel(
                      xTitle: ['12.1', '12.2', '12.3', '12.4', '12.5', '12.6'],
                      listData: listData,
                    ),
                    Row(
                      children: [
                        SizedBox(width: 30),
                        TDText(_billetData['chargingTime'].toString(),
                            font: TDTheme.of(context).fontBodySmall,
                            textColor: Color(0xFF65CEFF)),
                        const Expanded(child: SizedBox()),
                        TDText(_billetData['dischargingTime'].toString(),
                            font: TDTheme.of(context).fontBodySmall,
                            textColor: Color(0xFF65CEFF)),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 10),
            Padding(
              padding: const EdgeInsets.all(0.0),
              child: Container(
                padding: const EdgeInsets.all(16.0),
                decoration: BoxDecoration(
                  color: AppColors.cardColor,
                  borderRadius: BorderRadius.circular(8.0),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.2),
                      blurRadius: 6.0,
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        TDText(
                          '氧化烧损率（%）',
                          textColor: AppColors.textPrimary,
                          font: TDTheme.of(context).fontBodyMedium,
                        ),
                        // TDText(
                        //   '(m³)',
                        //   font: TDTheme.of(context).fontBodyMedium,
                        //   textColor: AppColors.textSecondary,
                        //   fontWeight: FontWeight.bold,
                        // ),
                      ],
                    ),
                    const SizedBox(height: 10), // Add some space
                    LineChartSample2(
                      spots: [20, 40, 90, 30, 80, 20],
                      xTitle: ['', '', '', '', '', ''], // 传递 xTitle 数据
                    ),
                    Row(
                      children: [
                        SizedBox(width: 30),
                        TDText(_billetData['chargingTime'].toString(),
                            font: TDTheme.of(context).fontBodySmall,
                            textColor: Color(0xFF65CEFF)),
                        const Expanded(child: SizedBox()),
                        TDText(_billetData['dischargingTime'].toString(),
                            font: TDTheme.of(context).fontBodySmall,
                            textColor: Color(0xFF65CEFF)),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ] else ...[
            SizedBox(height: 100),
            TDEmpty(
              type: TDEmptyType.plain,
              emptyText: '暂无内容',
              image: Container(
                width: 420,
                height: 160,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(
                        TDTheme.of(context).radiusDefault),
                    image: const DecorationImage(
                        image: AssetImage('assets/images/centre/empty.png'))),
              ),
            ),
          ]
        ],
      ),
    );
  }
}
